<template>
  <view class="th-form">
    <slot></slot>
  </view>
</template>

<script>
export default {
  name: 'thForm',
  components: {},
  data() {
    return {
      unValidMap: {},
    };
  },
  props: {
    labelWidth: {
      type: String,
      default: '3.85rem',
    },
    rules: {
      type: Object,
      default: () => {
        return {};
      },
    },
    model: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  created() {},
  methods: {
    validate(fn) {
      const unValidMap = {};
      Object.entries(this.rules).forEach((item) => {
        if (item[1].required) {
          if (item[1].validator) {
            const validatorRes = item[1].validator(this.model[item[0]]);
            if (validatorRes && !validatorRes.value) {
              unValidMap[item[0]] = item[1];
              if (validatorRes.message) {
                unValidMap[item[0]]['message'] = validatorRes.message;
              }
            }
          } else if (
            this.model[item[0]] === undefined ||
            this.model[item[0]] === '' ||
            this.model[item[0]] === null
          ) {
            unValidMap[item[0]] = item[1];
          }
        }
      });
      this.unValidMap = unValidMap;
      if (Object.keys(this.unValidMap).length) {
        fn(false, this.unValidMap);
      } else {
        fn(true);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.th-form {
  display: flex;
  flex-wrap: wrap;

  &::after {
    flex: 1;
    min-width: 540rpx;
    height: 0;
    margin: 0 24rpx;
    content: '';
  }
}
</style>
